package com.fanco.learn_datastruct_leetcode.juc;/**
 * @author qiaowang 2021/8/17
 */

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author fanco
 * @Desc 可重入锁Demo
 */
public class ReentrantLockDemo {
    public static void main(String[] args) {
        Phone phone = new Phone();
        reSyncTest(phone);

        System.out.println();
        System.out.println();

        Thread t3 = new Thread(phone);
        Thread t4 = new Thread(phone);
        t3.start();
        t4.start();
    }

    public static void reSyncTest(Phone phone) {
        new Thread(() -> {
            phone.sendSMS();

        }, "t1").start();

        new Thread(() -> {
            phone.sendSMS();

        }, "t2").start();
    }
}

class Phone implements Runnable {

    /**
     * synchronized 实现可重入锁
     */
    public synchronized void sendSMS() {
        System.out.println(Thread.currentThread().getName() + "\t" + "发信息");
        sendWechat();
    }

    public synchronized void sendWechat() {
        System.out.println(Thread.currentThread().getName() + "\t" + "发微信");
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    Lock lock = new ReentrantLock();
    @Override
    public void run() {
        sendQQ();
    }

    public void sendQQ () {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t" + "发QQ消息");
            sendMomo();
        } finally {
            lock.unlock();
        }
    }

    public void sendMomo() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t" + "发陌陌消息");
        } finally {
            lock.unlock();
        }
    }

}
